<template>
  <div class="setting-container">
    <div class="filter-container">
      <el-input v-model="listQuery.userName"
                placeholder="姓名"
                style="width: 200px;"
                class="filter-item"
                @keyup.enter.native="handleFilter" />
      <el-button v-waves
                 class="filter-item pan-btn light-blue-btn"
                 icon="el-icon-search"
                 @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item pan-btn green-btn"
                 style="margin-left: 10px;"
                 icon="el-icon-edit"
                 @click="handleCreate">
        新增
      </el-button>
      <el-button v-waves
                 :loading="downloadLoading"
                 class="filter-item pan-btn blue-btn"
                 icon="el-icon-download"
                 @click="handleDownload">
        导出
      </el-button>
    </div>
    <el-table :key="tableKey"
              v-loading="listLoading"
              :data="list"
              border
              fit
              highlight-current-row
              style="width: 100%;">
      <!-- :default-sort="{prop: 'timestamp', order: 'descending'}" -->
      <!-- @sort-change="sortChange"> -->
      <!-- <el-table-column label="创建时间"
                       prop="timestamp"
                       sortable
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="标签ID"
                       prop="tagId"
                       align="center">
        <!-- :class-name="getSortClass('id')"> -->
        <template slot-scope="{row}">
          <span>{{ row.tagId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="userId"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.userId  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="职位"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.userPost }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作"
                       align="center"
                       :col=6
                       class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary"
                     size="mini"
                     @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'"
                     size="mini"
                     type="danger"
                     @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0"
                :total="total"
                :page.sync="listQuery.page"
                :limit.sync="listQuery.limit"
                @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]"
               :visible.sync="dialogFormVisible"
               @close="temp.permissionType='none'"
               width="67%"
               top='3vh'>
      <el-form ref="dataForm"
               :rules="rules"
               :model="temp"
               label-position="left"
               :inline="true">
        <el-form-item label="标签ID"
                      prop="tagId">
          <el-input v-model="temp.tagId" />
        </el-form-item>
        <el-form-item label="姓名"
                      prop="userName">
          <el-input v-model="temp.userName" />
        </el-form-item>
        <el-form-item label="userId"
                      prop="userId">
          <el-input v-model="temp.userId" />
        </el-form-item>
        <el-form-item label="职位"
                      prop="userPost">
          <el-select v-model="temp.userPost"
                     placeholder="请选择">
            <el-option v-for="item in post"
                       :key="item.userPost"
                       :label="item.userPost"
                       :value="item.userPost">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限"
                      prop="permissionType">
          <el-tooltip class="item"
                      effect="dark"
                      content="设置安全区后，若标签处在安全区范围以外，则产生报警"
                      placement="bottom-start">
            <el-radio v-model="temp.permissionType"
                      label="safe"><span class='safe'>安全区</span></el-radio>
          </el-tooltip>
          <el-tooltip class="item"
                      effect="dark"
                      content="设置危险区后，若标签进入危险区，则产生报警"
                      placement="bottom">
            <el-radio v-model="temp.permissionType"
                      label="danger"><span class='danger'>危险区</span></el-radio>
          </el-tooltip>

          <el-radio v-model="temp.permissionType"
                    label="none">不设置</el-radio>
        </el-form-item>
      </el-form>
      <permission v-if="temp.permissionType==='safe'||temp.permissionType==='danger'"
                  @areaSelected="areaReceived"
                  ref='chart'
                  width="100%"
                  :areaSelected="temp.area"
                  :permissionType="temp.permissionType"></permission>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary"
                   @click="dialogStatus==='create'?createTag():updateTag()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Permission from '@/components/Map/Permission'
import { mapGetters } from 'vuex'
import {
  fetchList,
  getPost,
  createTag,
  updateTag,
  deleteTag
} from '@/api/setting'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'

import Pagination from '@/components/Pagination' // secondary package based on el-pagination
let count1 = 0
export default {
  name: 'setting',

  computed: {
    ...mapGetters(['name'])
  },
  components: { Pagination, Permission },
  directives: { waves },
  data() {
    // const validateTag = (rule, value, callback) => {
    //   if (value.length < 1) {
    //     console.log(value)
    //     callback(new Error('必须选择一项'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      tableKey: 0,
      list: null,
      permissionTypeA: 'safe',
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        userName: undefined
        // sort: '+id'
      },
      // sortOptions: [
      //   { label: 'ID Ascending', key: '+id' },
      //   { label: 'ID Descending', key: '-id' }
      // ],
      temp: {
        // timestamp: new Date(),
        tagId: undefined,
        userName: undefined,
        userPost: undefined,
        userId: undefined,
        permissionType: undefined,
        area: []
        // employeeId: undefined,
        // authority: []
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新建'
      },
      rules: {
        tagId: [{ required: true, message: '标签ID不能为空', trigger: 'blur' }],
        userName: [
          {
            required: true,
            message: '姓名不能为空',
            trigger: 'blur'
          }
        ]
        // employeeId: [
        //   { required: true, message: '工号不能为空', trigger: 'blur' }
        // ],
        // authority: [{ required: true, trigger: 'blur', validator: validateTag }]
      },
      downloadLoading: false,
      post: null,
      post_value: null
    }
  },
  created() {
    this.getList()
    this.getPost()
  },
  mounted() {
    setTimeout(() => {
      console.log(this.list)
    }, 1000)
  },
  methods: {
    getPost() {
      getPost().then(response => {
        console.log(response)
        this.post = response
        console.log(this.post)
      })
    },
    getList() {
      this.listLoading = false
      fetchList(this.listQuery).then(response => {
        console.log(response)
        this.list = response.data.items
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    // sortChange(data) {
    //   const { prop, order } = data
    //   if (prop === 'id') {
    //     this.sortByID(order)
    //   }
    // },
    // sortByID(order) {
    //   if (order === 'ascending') {
    //     this.listQuery.sort = '+id'
    //   } else {
    //     this.listQuery.sort = '-id'
    //   }
    //   this.handleFilter()
    // },
    resetTemp() {
      this.temp = {
        tagId: undefined,
        userName: undefined,
        userPost: undefined,
        userId: undefined,
        permissionType: undefined,
        area: undefined
        // employeeId: undefined,
        // authority: []
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.resetTemp()
      })
    },
    createTag() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createTag(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: this.temp.userName,
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleSelectTag(tag) {
      this.authorities.splice(this.authorities.indexOf(tag), 1)
      this.temp.authority.push(tag)
    },
    areaReceived(data) {
      this.temp.area = []
      console.log(data)
      this.temp.area = data
    },
    handleUpdate(row) {
      console.log(row)
      row.permissionType = this.permissionTypeA
      row.area = [
        [
          [5, 20],
          [5, 20]
        ],
        [
          [5, 18],
          [10, 26]
        ]
      ]
      this.temp = Object.assign({}, row) // copy obj

      console.log(this.temp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        // this.resetTemp()
      })
    },
    updateTag() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateTag(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: this.temp.tagId,
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      console.log(row)
      let obj = { tagId: row.tagId }
      deleteTag(obj).then(() => {
        this.$notify({
          title: row.tagId,
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        // const tHeader = ['时间', '标签ID', '姓名', '工号', '权限']
        const tHeader = ['时间', '标签ID', '姓名', '职位']
        const filterVal = [
          'timestamp',
          'tagId',
          'userName',
          'userPost'
          // 'employeeId',
          // 'authority'
        ]
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '标签-人员信息'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    // getSortClass: function(key) {
    //   const sort = this.listQuery.sort
    //   return sort === `+${key}` ? 'ascending' : 'descending'
    // },
    resetDateFilter() {
      this.$refs.filterTable.clearFilter('timestamp')
    },
    clearFilter() {
      this.$refs.filterTable.clearFilter()
    },
    formatter(row, column) {
      return row.address
    },
    filterTag(value, row) {
      // let count = 0
      console.log(value)
      row.authority.forEach(item => {
        if (item === value) {
          count1++
        }
      })
      console.log(count1)
      return count1 >= 2 ? true : false
    },
    filterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    filterItem(item) {
      if (item === '办公室') {
        return 'success'
      } else if (item === '会议室') {
        return 'warning'
      } else if (item === '工作区') {
        return 'info'
      } else if (item === '仓库') {
        return 'info'
      }
    }
  },
  watch: {
    'temp.permissionType': function(oldVal, newVal) {
      console.log(['safe', 'danger'].includes(oldVal))
      console.log(['safe', 'danger'].includes(newVal))
      if (
        ['safe', 'danger'].includes(oldVal) &&
        ['safe', 'danger'].includes(newVal)
      ) {
        this.$refs.chart.chart.dispatchAction({
          type: 'restore'
        })

        console.log(this.$refs.chart.chart.getOption())
        console.log(this.$refs.chart.chart)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.setting {
  position: relative;
  width: 100%;
  height: calc(100vh - 84px);
}
.safe {
  color: green;
}
.danger {
  color: red;
}
.tagHover {
  cursor: pointer;
}
</style>
